package com.red.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.red.pojo.model.LoginUser;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class JWTUtil {
    private final static String JWT_SECRET = "Hello JWT!";

    public static String createJWT(Object payload) {
        JSONObject jwtHeader = new JSONObject();
        jwtHeader.put("alg", "HS256");
        String jwtPayload = JSON.toJSONString(payload);

        String base64Header = Base64.getEncoder().encodeToString(jwtHeader.toJSONString().getBytes());
        String base64Payload = Base64.getEncoder().encodeToString(jwtPayload.getBytes(StandardCharsets.UTF_8));

        String signature = DigestUtils.md5DigestAsHex((jwtPayload + JWT_SECRET).getBytes());

        return base64Header + '.' + base64Payload + '.' + signature;
    }

    public static boolean verifyJWT(String jwt) {
        // Base64中存在+号，这个字符在URL中会变成空格，所以这里需要做个替换
        jwt = jwt.replaceAll(" ", "+");

        String jwtPayload = new String(Base64.getDecoder().decode(jwt.split("\\.")[1].getBytes()), StandardCharsets.UTF_8);
        String jwtSignature = jwt.split("\\.")[2];
        return DigestUtils.md5DigestAsHex((jwtPayload + JWT_SECRET).getBytes()).equals(jwtSignature);
    }

    public static <T> T getPayload(String jwt, Class<T> clazz) {
        jwt = jwt.replaceAll(" ", "+");

        String jwtPayload = new String(Base64.getDecoder().decode(jwt.split("\\.")[1].getBytes()), StandardCharsets.UTF_8);
        return JSONObject.parseObject(jwtPayload, clazz);
    }

    public static LoginUser getLoginUser(HttpServletRequest request) {
        String token = request.getHeader("token");

        if (token == null) {
            return null;
        }

        return getPayload(token, LoginUser.class);
    }
}

